import time

import RPi.GPIO as GPIO

from .drive import SetPwm, SetPin

GPIO.setmode(GPIO.BCM)


class DcMotor:
    # 树莓派BCM的2，3，4引脚对应PWM波
    PWM_Port = 2, 3, 4
    PWM_Freq = 10
    Dir_Port = (17, 27), (22, 10), (9, 11)

    def __init__(self):
        self.pwm_lst = [SetPwm(port, self.PWM_Freq) for port in self.PWM_Port]
        self.dir_control = self.get_dir_control()

    def get_dir_control(self):
        return [
            [SetPin(self.Dir_Port[0][0]), SetPin(self.Dir_Port[0][1])],
            [SetPin(self.Dir_Port[1][0]), SetPin(self.Dir_Port[1][1])],
            [SetPin(self.Dir_Port[2][0]), SetPin(self.Dir_Port[2][1])],
        ]

    def set_3_dir(self, dir_list):
        for index, value in enumerate(dir_list):
            if value is None:
                self.dir_control[index][0].change_voltage(False)
                self.dir_control[index][1].change_voltage(False)
                continue
            dir_flag = True if value else False
            self.dir_control[index][0].change_voltage(dir_flag)
            self.dir_control[index][1].change_voltage(not dir_flag)

    def set_3_dc(self, dc_list):
        for index, dc in enumerate(dc_list):
            if dc == 0:
                dc = 0.001
            self.pwm_lst[index].change_dc(dc)
